﻿using System;
using System.Collections.Generic;
using System.Linq;
using CoreVirtuoso.Helpers;
using VDS.RDF;
using VDS.RDF.Parsing;
using VDS.RDF.Storage;
using VirtuosoDal.Repositories.RdfRepositories.Interfaces.VirtuosoCore;

namespace VirtuosoDal.Repositories.RdfRepositories.VirtuosoCore
{
   public class GraphRepository : IGraphRepository
   {
      public void CreateGraph(string graphUri)
      {
         using (var virtuosoManager = new VirtuosoManager(ConnectionStringsHelper.GetVirtuosoConnectionString()))
         {
            virtuosoManager.Open(false);
            virtuosoManager.ExecuteNonQuery(String.Format("sparql CREATE GRAPH <{0}>", graphUri));
            virtuosoManager.Close(true);
         }
      }

      public void UploadGraph(string fileName, string graphUri)
      {
         Graph graph = new Graph();
         RdfXmlParser parser = new RdfXmlParser();
         parser.Load(graph, fileName);

         using (var virtuosoManager = new VirtuosoManager(ConnectionStringsHelper.GetVirtuosoConnectionString()))
         {
            virtuosoManager.UpdateGraph(graphUri, graph.Triples.ToList(), new List<VDS.RDF.Triple>());
         }
      }

      public void ClearGraph(string graphUri)
      {
         using (var virtuosoManager = new VirtuosoManager(ConnectionStringsHelper.GetVirtuosoConnectionString()))
         {
            virtuosoManager.Open(false);
            virtuosoManager.ExecuteNonQuery(String.Format("sparql CLEAR GRAPH <{0}>", graphUri));
            virtuosoManager.Close(true);
         }
      }

      public void AddTriplesToGraph(string graphUri, IEnumerable<Triple> triples)
      {
         using (var virtuosoManager = new VirtuosoManager(ConnectionStringsHelper.GetVirtuosoConnectionString()))
         {
            virtuosoManager.UpdateGraph(graphUri, triples, null);
         }
      }

      public void AddTriplesToGraph(VirtuosoManager virtuosoManager, string graphUri, IEnumerable<Triple> triples)
      {
         virtuosoManager.UpdateGraph(graphUri, triples, null);
      }
   }
}